package server

import (
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"network_study3/src/server/api"
	"network_study3/src/server/moudle"
	"strconv"
)

func Start() {
	fmt.Println("http 服务端启动...")

	/*// 登录测试
	func() {
		body, err := api.Login("lisis", "123456")
		if err != nil {
			log.Println(err)
		}
		fmt.Println(body)
	}()*/

	/*// 注册测试
	func() {
		body, err := api.Register(moudle.SysUser{
			Name:     "小红",
			Sex:      false,
			UserName: "xiaohong",
			Password: "111111",
			Phone:    "13526023111",
			Email:    "13260235210@qq.com",
		})
		if err != nil {
			log.Println(err)
		}
		fmt.Println(body)
	}()*/

	/*// 注销用户
	moudle.SysUserRemove(2)*/

	/*// 查询用户列表 测试
	func() {
		for _, v := range moudle.SysUserAll() {
			fmt.Println(v)
		}
	}()*/

	// 定义服务端接口
	http.HandleFunc("/login", loginHandler)
	// 查询用户列表
	http.HandleFunc("/userAll", sysUserAllHandler)
	// 注册用户
	http.HandleFunc("/register", registerHandler)
	// 注销用户
	http.HandleFunc("/cancel", cancelHandler)

	// 启动服务端
	if err := http.ListenAndServe(":60000", nil); err != nil {
		fmt.Println("服务端启动错误：", err)
	}

}

// API 响应结构体
type Result struct {
	Code    int         `json:"code"`
	Success bool        `json:"success"`
	Message string      `json:"message"`
	Data    interface{} `json:"data,omitempty"`
}

// 发送JSON响应，支持任意类型
func send(w http.ResponseWriter, data Result) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(data.Code)
	json.NewEncoder(w).Encode(data)
}

/**
 * 登录 处理
 */
func loginHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodGet {
		send(w, Result{500, false, "请求类型不是GET!", nil})
		return
	}

	query := r.URL.Query()
	userName := query.Get("userName")
	passWord := query.Get("passWord")

	body, err := api.Login(userName, passWord)
	if err != nil {
		send(w, Result{500, false, err.Error(), nil})
		return
	}

	send(w, Result{200, true, body, nil})
}

/**
 * 查询用户列表 处理
 */
func sysUserAllHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodGet {
		send(w, Result{500, false, "请求类型不是GET!", nil})
		return
	}

	send(w, Result{200, true, "操作成功！", moudle.SysUserAll()})
}

/**
 * 注册用户 处理
 */
func registerHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodPost {
		send(w, Result{500, false, "请求类型不是POST!", nil})
		return
	}

	body, err := io.ReadAll(r.Body)
	if err != nil {
		send(w, Result{500, false, err.Error(), nil})
		return
	}
	defer r.Body.Close()

	fmt.Println("收到请求参数：", string(body))

	// json字符串转结构体
	var param moudle.SysUser
	if err := json.Unmarshal(body, &param); err != nil {
		send(w, Result{500, false, err.Error(), nil})
		return
	}

	fmt.Println(param)

	body2, err := api.Register(moudle.SysUser{
		Name:     param.Name,
		Sex:      param.Sex,
		UserName: param.UserName,
		Password: param.Password,
		Phone:    param.Phone,
		Email:    param.Email,
	})
	if err != nil {
		send(w, Result{500, false, err.Error(), nil})
		return
	}

	send(w, Result{200, true, body2, nil})
}

/**
 * 注销用户 处理
 */
func cancelHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodGet {
		send(w, Result{500, false, "请求类型不是GET!", nil})
		return
	}

	// 获取GET请求参数
	id := r.URL.Query().Get("id")
	fmt.Println("获取请求参数id:", id)
	num, err := strconv.Atoi(id)
	if err != nil {
		send(w, Result{500, false, err.Error(), nil})
	}
	moudle.SysUserRemove(num)
	send(w, Result{200, true, "", nil})
}
